﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hengbei.DAL.Models;
using Hengbei.DAL;
using System.Data;
using System.Data.Entity.Validation;
using System.Diagnostics;

namespace Hengbei.BLL
{
    public static class ArticleService
    {
        private static HengbeiEntities context;

        public static HengbeiEntities Context
        {
            get
            {
                if (context == null)
                {
                    context = new HengbeiEntities();
                }
                return context;
            }
            set { context = value; }
        }

        public static Article GetArticleByID(int ID)
        {
            Article article = Context.Articles.Where(a => a.ID == ID).FirstOrDefault();
            if (article == null)
            {
                article = new Article();
            }
            return article;
        }

        public static int SaveArticle(Article article)
        {
            int result = 0;
            var entity = Context.Entry(article);
            if (entity.State == EntityState.Detached)
            {
                Context.Articles.Attach(article);
                entity = Context.Entry(article);
            }
            entity.State = article.EntityState;
            try
            {
                result = Context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            return result;
        }
    }
}
